package com.teamc.team.service.impl;

import com.teamc.team.mapper.UserMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.security.core.userdetails.User;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @author ding
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper mapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @SneakyThrows
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        com.teamc.team.entity.User user = mapper.getUser(s);
        if (user == null) {
            throw new Exception("用户名不存在!");
        }
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        //这里应该动态的从数据库里读取该用户的权限然后进行添加
        if (user.getUserEnabled() == 0 || user.getUserEnabled() == 1 ) {
            authorities.add(new SimpleGrantedAuthority("USER"));
        } else if (user.getUserEnabled() == 2 ) {
            authorities.add(new SimpleGrantedAuthority("ADMIN"));
        }
        return new User(user.getUserId(),passwordEncoder.encode(user.getUserPassword()),authorities);
    }
}
